package com.lovo.bbs.controller;

import com.lovo.bbs.bean.User;
import com.lovo.bbs.bean.form.UserForm;
import com.lovo.bbs.result.GlobalHandleException;
import com.lovo.bbs.result.ResponseResult;
import com.lovo.bbs.result.ResultCode;
import com.lovo.bbs.result.UserValid;
import com.lovo.bbs.service.UserService;
import com.lovo.bbs.util.JWTUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;

@RestController
@RequestMapping("/users")
@Tag(name = "用户控制器UserController")
@SecurityRequirement(name = "bearer-key")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    @Operation(summary = "登录login")
    @ResponseResult
    public Object login(HttpServletRequest request, @RequestBody UserForm userForm) throws GlobalHandleException {
//        HttpSession session = request.getSession();
        User user = userService.login(userForm.getUsername(),DigestUtils.sha256Hex(userForm.getPwd()));
        if(user != null){
//            session.setAttribute("user",user);
            String token = JWTUtil.createToken(user.getUsername(),user.getPwd(), Calendar.MINUTE,30);
            return token;
        }else{
            throw new GlobalHandleException(ResultCode.USER_LOGIN_ERROR);
        }
    }

    @GetMapping
    @Operation(summary = "根据用户名查询用户")
    @ResponseResult
    public Object getByUsername(String username) throws GlobalHandleException {
        User user =  userService.getByUsername(username);
        if(user == null){
            return null;
        }else{
            throw new GlobalHandleException(ResultCode.USER_NOT_EXIST);
        }
    }
    @PostMapping()
    @Operation(summary = "注册")
    @ResponseResult
    public Object reg(@RequestBody UserForm userForm){
        User user = new User();
        BeanUtils.copyProperties(userForm,user);
        user.setPwd(DigestUtils.sha256Hex(user.getPwd()));
        return userService.save(user);

    }

    @GetMapping("/token")
    @ResponseResult
    @UserValid
    public Object getUserByToken(HttpServletRequest request){
        return request.getAttribute("user");
    }
}
